'use strict';

const Controller = require('egg').Controller;

class GroupController extends Controller {

  async getGroupList(){
    let id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
  });
  let result=await this.ctx.service.group.getGroupList(id);
  this.ctx.body=result;
  }
  
  //搜索群聊并判断自己在不在群里
  async groupSearch() {
    let keyword=this.ctx.request.body.keyword;//接收前端搜索词
    //待解决问题：如何同时将查询结果和判断结果返回
    let result=await this.ctx.service.group.search(keyword);//调用搜索函数
    this.ctx.body=result
  }

  async groupDetail(){
    let user_id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
    });//接收本用户id
    let group_id=this.ctx.params.id;;//接收群id
    let groupDetail=await this.ctx.service.group.groupDetail(user_id,group_id);
    this.ctx.body = groupDetail
  }

  async getGroupMembers(){
    let group_id=this.ctx.params.id;
    let groupMembers=await this.ctx.service.group.getGroupMembers(group_id);
    this.ctx.body=groupMembers;
  }
  //建群
  async createGroup(){
    let user_id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
    });//接收本用户id
    let groupinfo=this.ctx.request.body;
    let createGroupResult=await this.ctx.service.group.createGroup(user_id,groupinfo);
    if(createGroupResult){
      this.ctx.body="群聊创建成功！"
    }else{
      this.ctx.body="群聊创建失败！"
    }
  }
  
  //加入群聊
  async applyGroup(){
    let user_id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
    });//接收本用户id
    let group_id=this.ctx.request.body.group_id;
    let name=this.ctx.request.body.name;
    let applyResult=await this.ctx.service.group.applyGroup(user_id,group_id,name);
    if(applyResult){
      this.ctx.body="已加入该群聊！"
    }else{
      this.ctx.body="加入群聊失败！"
    }
  }

  //退出群聊
  async deleteGroup(){
    let user_id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
    });//接收本用户id
    let group_id=this.ctx.params.group_id;
    let deleteResult=await this.ctx.service.group.deleteGroup(user_id,group_id);
    if(deleteResult){
      this.ctx.body="已退出群聊！"
    }else{
      this.ctx.body="退出群聊失败！"
    }
  }
}

module.exports = GroupController;